package org.example.filter;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashSet;
import java.util.Set;

@WebFilter(filterName = "LoginFilter", urlPatterns = "/*")
public class LoginFilter implements Filter {
    private final Set<String> excludedUrls = new HashSet<>();

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        // 初始化时添加不需要登录的路径到排除列表
          // 假设/public下的所有资源都不需要登录
        excludedUrls.add("/logout");
        excludedUrls.add("/login");
        excludedUrls.add("/index");

    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse res = (HttpServletResponse) response;

        String path = req.getRequestURI().substring(req.getContextPath().length());

        // 检查当前请求路径是否在排除列表中
        if (isExcluded(path)) {
            chain.doFilter(request, response);  // 如果在排除列表中，则允许请求通过
            return;
        }

        // 检查用户是否已登录
        if (req.getSession().getAttribute("user") != null) {
            chain.doFilter(request, response);  // 用户已登录，允许请求继续
        } else {
            res.sendRedirect(req.getContextPath() + "/login");  // 用户未登录，重定向到登录页面
        }
    }

    @Override
    public void destroy() {
        // 过滤器销毁时的代码，如果需要的话
    }

    //检查请求路径是否在排除列表中,@return 如果路径被排除返回 true，否则返回 false
    private boolean isExcluded(String path) {
        return excludedUrls.stream().anyMatch(path::startsWith);
    }
}